<template>
  <div class="file_project">
    <div class="select_Team">
      <div class="demo-input-suffix">
        <el-input
          class="search_button"
          placeholder="文件名"
          v-model="change"
          @keyup.enter.native="Project_documents_onSearch"
        >
          <i
            slot="suffix"
            class="el-icon-search el-input__icon"
            @click="Project_documents_onSearch"
          ></i>
        </el-input>

        <button class="delete" @click="Project_documents_cancel">取消</button>
      </div>
      <!-- <el-upload id="Incubation_file_upload" action="#">
        <i class="el-icon-plus"></i>
      </el-upload> -->
      <span v-show="percent != 0">上传进度{{ percent }}%</span>

      
      <el-dropdown
        v-show="percent == 0"
        @command="handleCommand"
        class="moreChose"
        trigger="click"
        placement="bottom-start"
      >
        <i class="el-icon-plus" style="font-size: 35px; margin-right: 20px"></i>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item
            v-for="item in option"
            :key="item.id"
            :command="item.id"
          >
            <el-upload
              accept=".xls,.xlsx,.ppt,.pdf,.docx,.doc,.pptx"
              :show-file-list="false"
              :on-change="changeHandle"
              :http-request="upload_file"
              :auto-upload="true"
              :before-upload="beforeAvatarUpload"
              action="#"
            >
              <span>{{ item.fileType }}</span>
            </el-upload>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div class="project_file">
      <!-- <span class="project_file_title"> 66666 </span> -->
      <div class="file_message" v-for="(item, index) in file_data" :key="index">
        <div class="project_name">
          <img :src="item.url" alt="" title="添加WPS文件" />
          <span>文件名:{{ item.fileName }}</span>
        </div>
        <span class="people">上传人:{{ item.realName }}</span>
        <span class="dateTime">上传日期:{{ item.createTime }}</span>

        <el-dropdown class="moreChose" trigger="click" placement="bottom-start">
          <span class="el-dropdown-link"> ... </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              @click.native="remove_document_Indexes(item.id)"
              command="删除文档"
              >删除文档</el-dropdown-item
            >

            <el-dropdown-item
              @click.native="download_document(item.id, item.fileName)"
              divided
              command="下载到本地"
              >下载到本地</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>

<script>
import COS from "cos-js-sdk-v5";
export default {
  props: {},
  components: {},
  data() {
    return {
      file_data: [],
      fileList: [],
      change: "",
      option: "",
      file: {
        url: "",
        fileName: "",
        incubationFileTypeId: "",
        fileSize: "",
      },
      Incubation_file: "",
      percent: 0,
    };
  },
  methods: {
    //搜索
    Project_documents_onSearch() {
      this.get_Incubation_file();
    },
    Project_documents_cancel() {
      this.change = "";
      this.get_Incubation_file();
    },

    handleCommand(command) {
      this.file.incubationFileTypeId = command;
    },

    // 删除文档
    async remove_document_Indexes(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }

      const { data: res } = await this.$http({
        headers: { "Content-Type": "application/json;charset=UTF-8" },
        method: "get",
        url: "/api/attendance/deletefile",
        params: {
          id: id,
        },
      });

      this.$message.success(res.msg);
      this.get_Incubation_file();
    },

    // //下载到本地
    async download_document(id, name) {
      const { data: res } = await this.$http({
        headers: { "Content-Type": "application/json;charset=UTF-8" },
        method: "get",
        url: "/api/attendance/downloadfile",
        params: {
          id: id,
        },
      });
      console.log(res.msg);
      // window.open(res.msg);

      this.getBlob(res.msg).then((blob) => {
        this.saveAs(blob, name);
      });
    },

    getBlob(url, cb) {
      return new Promise((resolve) => {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response);
          }
        };
        xhr.send();
      });
    },

    saveAs(blob, filename) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
      } else {
        const link = document.createElement("a");
        const body = document.querySelector("body");
        link.href = window.URL.createObjectURL(blob);
        link.download = filename;
        // fix Firefox
        link.style.display = "none";
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      }
    },

    async get_Incubation_file() {
      const self = this;

      const { data: res } = await this.$http({
        headers: { "Content-Type": "application/json;charset=UTF-8" },
        method: "get",
        url: "/api/attendance/getAllFileInfo",
        params: {
          fileName: self.change,
        },
      });

      this.file_data = res.msg;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 20;

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 20MB!");
      }
      return isLt2M;
    },
    changeHandle(file) {
      this.file.fileName = file.name;
      this.file.fileSize = Math.round((file.size / 1048576) * 100) / 100;

      // this.file.fileSize = file.size;

      this.Incubation_file = file.raw;
    },
    async upload_file() {
      // 创建COS实例  获取签名
      //这里写你们后端提供的请求接口即可，这里调用的接口是为了获取tmpSecretId、tmpSecretKey、sessionToken、expiredTime这些值
      const { data: res1 } = await this.$http({
        headers: { "Content-Type": "application/json;charset=UTF-8" },
        method: "get",
        url: "/api/upload/getSecretKey",
      });

      const data = res1.credentials;
      const cos = new COS({
        // 必选参数
        getAuthorization: (options, callback) => {
          const obj = {
            TmpSecretId: data.tmpSecretId,
            TmpSecretKey: data.tmpSecretKey,
            XCosSecurityToken: data.sessionToken,
            StartTime: res1.startTime, // 时间戳，单位秒，如：1580000000
            ExpiredTime: res1.expiredTime, // 时间戳，单位秒，如：1580000900
          };
          callback(obj);
        },
      });

      // cos.setEncoding("GBK");

      // 上传图片  其中Bucket 和 Region找你们负责人拿，Bucke和Region是由公司负责人使用公司账户，登入腾讯云，获取回来的。
      //key 在前面加上路径写法可以生成文件夹
      cos.putObject(
        {
          Bucket: "fuhuaqi-1311373154" /* 必须 */,
          Region: "ap-guangzhou" /* 存储桶所在地域，必须字段 */,
          Key: "/yourself_check_file/" + new Date().getTime() + this.file.fileName /* 必须 */,
          StorageClass: "STANDARD",
          Body: this.Incubation_file, // 上传文件对象
          onProgress: (progressData) => {
            this.percent = progressData.percent * 100;
          },
        },
        (err, data) => {
          const url = "https://" + data.Location;
          this.file.url = url;

          console.log(url);

          if (url != null) {
            this.upload_file_data();
          }
        }
      );
    },

    //上传到后端
    async upload_file_data() {
      const self = this;

      const { data: res } = await this.$http({
        headers: { "Content-Type": "application/json;charset=UTF-8" },
        method: "post",
        url: "/api/attendance/uploadfile",
        data: self.file,
      });

      if (res.code == 200) {
        this.$message.success(res.msg);
        this.percent = 0;

        this.Incubation_file = "";
        this.file.url = "";
        this.file.fileName = "";
        this.file.incubationFileTypeId = "";
        this.file.fileSize = "";

        this.get_Incubation_file();
        return;
      }

      console.log("asdasdasdaasd");
      this.$message.err("上传失败");
      this.percent = 0;
    },
  },
  async created() {
    this.get_Incubation_file();

    const { data: res } = await this.$http({
      headers: { "Content-Type": "application/json;charset=UTF-8" },
      method: "get",
      url: "/api/attendance/getfiletype",
    });

    this.option = res.msg;
  },
};
</script>

<style lang="less">
.file_project {
  width: 100%;
  height: 99%;
  // background-color: rgb(133, 36, 36);
  overflow: auto;
  display: flex;
  flex-direction: column;
  .select_Team {
    width: 100%;
    // background-color: rgb(224, 15, 15);
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
  }
  .demo-input-suffix {
    display: flex;
    margin-left: 15px;
    height: 10px;
    width: 400px;

    .el-icon-search {
      color: blue;
      cursor: pointer;
    }
    .delete {
      width: 100px;
      height: 40px;
      border: none;
      background-color: white;
      color: rgb(0, 110, 225);
      cursor: pointer;
    }
  }
}

.project_file {
  width: 97%;
  padding: 10px;
  background-color: rgb(255, 255, 255);
  display: flex;
  // height: 90%;
  margin: 0 auto;
  margin-top: 23px;
  border-radius: 10px;
  box-shadow: 5px 5px 10px #d9d9d9, -5px -5px 10px #ffffff;
  flex-direction: column;
  overflow: auto;
  //标题
  .project_file_title {
    // background-color: rgb(224, 18, 18);
    width: 97%;
    height: 50px;
    display: flex;
    line-height: 50px;
    margin-left: 3%;
    font-size: 25px;
    font-weight: bold;
    flex-direction: row;
  }
  //行
  .file_message {
    // background-color: rgb(216, 37, 37);
    width: 100%;
    height: 50px;
    line-height: 50px;
    display: flex;
    justify-content: space-between;
    margin: 0px auto;
    margin-bottom: 5px;
    .project_name {
      display: flex;
      width: 60%;
      height: 50px;
      img {
        height: 30px;
        width: 30px;
        margin-top: 10px;
      }
      span {
        margin-left: 40px;
        height: 50px;
        line-height: 50px;
      }
    }
    .people {
      width: 22%;
    }
    .dateTime {
      width: 22%;
      // background-color: rgb(194, 20, 20);
    }
    .moreChose {
      width: 5%;
      height: 50px;
      display: flex;

      span {
        height: 50px;
        // line-height: 50px !important;
        font-size: 40px;
        display: flex;
        top: 0px;
        transform: translate(0, -27%);
        cursor: pointer;
      }
    }
  }
}

.project_file::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background: #fff;
}
.project_file::-webkit-scrollbar {
  width: 6px;
}

.project_file:hover::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
}
</style>